<?php

class Loader {
    
    /**
     * @var      array
     */
    protected static $classPath;
    protected static $cacheFileName = '/cache/classes_cache.php';
    
    
    /**
     * @param    string $ClassName    
     * @return   void
     */
    static public function load($ClassName) {
        if (empty(self::$classPath)) {
            self::initIncludePath();
            if (!is_readable(ROOT . self::$cacheFileName)) {
                self::initCacheFile();
            }
            self::$classPath = include(ROOT . self::$cacheFileName);
        }

        if(array_key_exists($ClassName, self::$classPath)){
            include_once(ROOT . self::$classPath[$ClassName]);
        }
//        替代方法
//        foreach (self::$classPath as $class => $file) {
//            if ($class == $ClassName) {
//                include_once(ROOT . $file);
//                break;
//            }
//        }
    }
    
    /**
     * @return   void
     */
    static public function initIncludePath() {
        set_include_path(
            ROOT.'/libs/core'.PATH_SEPARATOR.
            ROOT.'/libs/vendor'.PATH_SEPARATOR.
            ROOT.'/libs/vendor/PEAR'.PATH_SEPARATOR.
            ROOT.'/libs/classes'
        );
    }
    
    /**
     * @return   void
     */
    static public function initCacheFile() {
        
        if(!file_exists(ROOT . self::$cacheFileName)) {
            include_once('File/Find.php');

            //$cache = fopen(ROOT . self::$cacheFileName, 'w');
            //fwrite($cache, "<?php\n\n\n");
            $fp = "<?php\n\n";
            $date   = date('Y-m-d H:i:s');
            $fp .="/**create:\n $date\n*/\n";
            //fwrite($cache, "return array(\n\n");
            $fp .= "return array(\n\n";
            $dirs = array('config', 'libs', 'modules');
            //$classPath = array();

            foreach ($dirs as $dir) {
                $files = File_Find::search('~.*\.php$~i', ROOT.DIRECTORY_SEPARATOR.$dir, 'perl');
                foreach ($files as $file) {
                    preg_match_all('~^\s*(?:abstract\s+|final\s+)?(?:class|interface)\s+(\w+)~mi', file_get_contents($file), $classes);
                    foreach ($classes[1] as $class) {
                        //$file   = str_replace(ROOT, '', $file);
                        $fp .= "\t'$class' => '$file',\n";
                        //$classPath[$class] = $file;
                    }
                }
            }
            $fp  = str_replace(ROOT, '', $fp);
            $fp  = str_replace('\\', '/', $fp);
            $fp .=");\n\n";
            file_put_contents(ROOT . self::$cacheFileName, $fp);
            //print_r($classPath);
        }
    }

    /**
     * 自动加载方法
     * @param <type> $fun
     */
    public function autoLoadFunction($fun){
        
    }
}

